package com.sun.hunk.web.filter;

import com.sun.hunk.hibernate.BaseHibernateDAO;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.hibernate.StaleObjectStateException;

public class HibernateSessionRequestFilter extends BaseHibernateDAO implements Filter {

    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
            throws IOException, ServletException {
        
        try {
            getCurrentSession().beginTransaction();
            // Call the next filter (continue request processing)
            chain.doFilter(request, response);
            
            // Commit and cleanup
            getCurrentSession().getTransaction().commit();
      //      getCurrentSession().close();

        } catch (StaleObjectStateException staleEx) {        	
            // Rollback, close everything, possibly compensate for any permanent changes
            // during the conversation, and finally restart business conversation. Maybe
            // give the user of the application a chance to merge some of his work with
            // fresh data... what you do here depends on your applications design.
            throw staleEx;
        } catch (Throwable ex) {        
            ex.printStackTrace();
            System.out.println("INSDIE CATCH ERROR Throwable1");
            try {
                if (getCurrentSession().getTransaction().isActive()) {
                	
                    System.out.println("Trying to rollback database transaction after exception");
                    getCurrentSession().getTransaction().rollback();
                }
            } catch (Throwable rbEx) {
            	System.out.println("INSDIE CATCH ERROR Throwable2");
                System.err.println("Could not rollback transaction after exception! " + rbEx);
            }

            // Let others handle it... maybe another interceptor for exceptions?
            System.out.println("INSDIE CATCH ERROR Throwable ENDCXV");
            throw new ServletException(ex);
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        //this.initializeSessionFactory();
    }

    public void destroy() {}

}